package com.sctvcloud.dongqu.ui.activities;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.canyinghao.canrefresh.CanRefreshLayout;
import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.SharedPreferencesUtil;
import com.sctvcloud.dongqu.R;
import com.sctvcloud.dongqu.application.Constances;
import com.sctvcloud.dongqu.base.BaseActivity;
import com.sctvcloud.dongqu.beans.AFileItem;
import com.sctvcloud.dongqu.beans.FProgram;
import com.sctvcloud.dongqu.beans.FSearch;
import com.sctvcloud.dongqu.beans.LiveItem;
import com.sctvcloud.dongqu.beans.NewsItem;
import com.sctvcloud.dongqu.beans.SearchKeyWords;
import com.sctvcloud.dongqu.beans.SearchResult;
import com.sctvcloud.dongqu.beans.Titles;
import com.sctvcloud.dongqu.beans.TopicItem;
import com.sctvcloud.dongqu.http.AbsNetCallBack;
import com.sctvcloud.dongqu.http.NetUtils;
import com.sctvcloud.dongqu.ui.adapter.SearchHistoryAdapter;
import com.sctvcloud.dongqu.ui.adapter.SearchHotAdapter;
import com.sctvcloud.dongqu.ui.adapter.SearchResultAdapter;
import com.sctvcloud.dongqu.ui.util.IListShowData;
import com.sctvcloud.dongqu.ui.util.RBaseItemDecoration;
import com.sctvcloud.dongqu.ui.utils.KeyBoardUtils;
import com.sctvcloud.dongqu.ui.utils.TitleUtils;
import com.sctvcloud.dongqu.ui.utils.UiListMarginUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 搜索页
 */
public class SearchActivity extends BaseActivity implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener, OnItemInternalClick {
    @BindView(R.id.search_key_ct)
    protected CustomFontEditText search_ct;
    @BindView(R.id.search_view_ll)
    protected LinearLayout view_ll;
    @BindView(R.id.search_history_rl)
    protected RelativeLayout histories_rl;
    @BindView(R.id.search_noresult_cv)
    protected CustomFontTextView no_result_tv;
    @BindView(R.id.search_history_list)
    protected RecyclerView search_history_list;
    @BindView(R.id.layout_result)
    protected LinearLayout result_ll;
    @BindView(R.id.search_refresh)
    protected CanRefreshLayout refreshLayout;
    @BindView(R.id.can_content_view)
    protected RecyclerView search_result_list;
    @BindView(R.id.search_hot_gl)
    protected RecyclerView hot_list;
    @BindView(R.id.search_result_no_result)
    protected CustomFontTextView no_result;
    private LinearLayoutManager searchResultManager;
    private LinearLayoutManager searchHisManger;
    private GridLayoutManager hotManager;
    private SearchResultAdapter searchResultAdapter;
    private SearchHistoryAdapter searchHisAdapter;
    private ArrayList<SearchKeyWords> al_hot;
    private SearchHotAdapter hotAdapter;
    public static final String HISTORY_KEY = "history_keys";
    private String historyKeys;
    private AlertDialog dialog;
    public static final int REQUEST_CODE = 0;
    public static final int RESULT_CODE = 1;
    private int index = 0;
    private int count = 10;
    private final static String[] typeList = {"新闻", "专题", "直播", "主播"};

    private List<String> typedata;
    /**
     * TextView选择框
     */
    @BindView(R.id.tv_type_menu)
    protected TextView mSelectTv;

    /**
     * popup窗口里的ListView
     */
    private ListView mTypeLv;

    /**
     * popup窗口
     */
    private PopupWindow typeSelectPopup;

    /**
     * 数据适配器
     */
    private ArrayAdapter<String> testDataAdapter;

    private int type = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        typedata = Arrays.asList(typeList);
        initView();
        setHistoryKey();
    }

    private void initView() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        searchResultManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        search_result_list.setLayoutManager(searchResultManager);
        search_result_list.addItemDecoration(new RBaseItemDecoration(0));
        search_result_list.setItemAnimator(new DefaultItemAnimator());
        searchHisManger = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        search_history_list.setLayoutManager(searchHisManger);
        search_history_list.setItemAnimator(new DefaultItemAnimator());
        search_history_list.addItemDecoration(new RBaseItemDecoration(2));
        searchHisManger.setSmoothScrollbarEnabled(true);
        searchHisManger.setAutoMeasureEnabled(true);
        search_history_list.setHasFixedSize(true);
        search_history_list.setNestedScrollingEnabled(false);
        hotManager = new GridLayoutManager(this, 3);
        hot_list.setLayoutManager(hotManager);
        hot_list.setItemAnimator(new DefaultItemAnimator());
        hotManager.setSmoothScrollbarEnabled(true);
        hotManager.setAutoMeasureEnabled(true);
        hot_list.setHasFixedSize(true);
        hot_list.setNestedScrollingEnabled(false);
        getHotList();
        search_ct.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                if (charSequence.length() > 0) {
                    search_ct.setSelection(charSequence.length());
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            String key = search_ct.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("搜索关键词不能为空");
                return false;
            }
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "主动搜索"));
            GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);

            refreshLayout.autoRefresh();
            addHistory(key);

        }
        return super.dispatchKeyEvent(event);
    }


    @OnClick(value = {R.id.search_speak_ll, R.id.search_speak_iv, R.id.search_cancel, R.id.tv_type_menu})
    public void speakClick(View view) {
        switch (view.getId()) {
            case R.id.search_speak_ll:
            case R.id.search_speak_iv:
                Intent speakIntent = new Intent(this, SpeakActivity.class);
                search_ct.setText("");
                startActivityForResult(speakIntent, REQUEST_CODE);
                break;
            case R.id.search_cancel:
                finish();
                break;
            case R.id.tv_type_menu:
                initSelectPopup();
                if (typeSelectPopup != null && !typeSelectPopup.isShowing()) {
                    typeSelectPopup.showAsDropDown(mSelectTv, 0, -2, Gravity.RIGHT);
                }
                break;
        }
    }

    @Override
    public void onLoadMore() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.loadMoreComplete();
        } else {
            index++;
            searchForPage(search_ct.getText().toString().trim());
        }
    }

    @Override
    public void onRefresh() {
        index = 0;
        refreshLayout.setLoadMoreEnabled(true);
        search(search_ct.getText().toString().trim());
    }

    /**
     * 获取热门搜索数据
     */
    private void getHotList() {
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("siteNumber", Constances.SITE_ID);
        NetUtils.getNetAdapter().getHotKeyWords(getOwnerName(), param, new AbsNetCallBack<SearchKeyWords>(SearchKeyWords.class) {
            @Override
            public void onSuc(SearchKeyWords searchKeyWords) {
                if (searchKeyWords != null) {
                    if (!TextUtils.isEmpty(searchKeyWords.getKeywords())) {
                        setHotKeys(searchKeyWords.getKeywords());
                    }
                }
            }
        });
    }

    /**
     * 设置热门搜索
     *
     * @param keywords
     */
    private void setHotKeys(String keywords) {
        String[] keyWordsList = keywords.split(",");
        ArrayList<SearchKeyWords> keyList = new ArrayList<>();
        SearchKeyWords search = null;
        for (int i = 0; i < keyWordsList.length; i++) {
            search = new SearchKeyWords();
            search.setKeywords(keyWordsList[i]);
            keyList.add(search);
        }
//        for (int i = 0; i < keyList.size(); i++) {
//            if (i > 6) {
//                break;
//            }
        if (hotAdapter == null) {
            new UiListMarginUtils().setMargin(this, hot_list, R.dimen.item_list_margin_left, R.dimen.item_list_margin_left);
            hotAdapter = new SearchHotAdapter(this, keyList);
            hotAdapter.setItemInternalClick(hotItemClick);
            hot_list.setAdapter(hotAdapter);
        } else {
            hotAdapter.setData(keyList);
        }
    }

    /**
     * 将搜索关键词保存
     * @param key
     */
    private void addHistory(String key) {
        String historyKeys = (String) SharedPreferencesUtil.getParam(this, HISTORY_KEY, "");
        String[] oldStr = historyKeys.split(";");
        List<String> strList = Arrays.asList(oldStr);
        ArrayList<String> resultStrList = new ArrayList<>();
        resultStrList.add(key);
        for (String str : strList) {
            if (!str.equals(key)) {
                resultStrList.add(str);
            }
        }
        String resultStr = "";
        for (int i = 0; i < resultStrList.size(); i++) {
            if (i < 5) {
                if (i == resultStrList.size() - 1) {
                    resultStr = resultStr + resultStrList.get(i);
                } else {
                    resultStr = resultStr + resultStrList.get(i) + ";";
                }
            } else {
                break;
            }
        }
        SharedPreferencesUtil.setParams(this, HISTORY_KEY, resultStr);
    }

    /**
     * 设置显示搜索历史关键词
     */
    private void setHistoryKey() {
        historyKeys = (String) SharedPreferencesUtil.getParam(this, HISTORY_KEY, "");
        if (TextUtils.isEmpty(historyKeys)) {
            no_result_tv.setVisibility(View.VISIBLE);
            search_history_list.setVisibility(View.GONE);
        } else {
            no_result_tv.setVisibility(View.GONE);
            search_history_list.setVisibility(View.VISIBLE);
            final String[] keys = historyKeys.split(";");
            ArrayList<SearchKeyWords> al_history = new ArrayList<>();
            SearchKeyWords searchKeys = null;
            for (int i = 0; i < keys.length; i++) {
                searchKeys = new SearchKeyWords();
                searchKeys.setKeywords(keys[i]);
                al_history.add(searchKeys);
            }
            if (searchHisAdapter == null) {
                searchHisAdapter = new SearchHistoryAdapter(this, al_history).setItemInternalClick(hisOnItemClick);
                search_history_list.setAdapter(searchHisAdapter);
            } else {
                searchHisAdapter.setData(al_history);
            }

        }
    }

    /**
     * 点击搜索按钮，搜索关键词相关
     * @param keyword
     */
    private void search(String keyword) {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", index);
        param.put("option", 0);
        param.put("count", count);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null&& (ListUtils.isListValued(fSearch.getAnchorList()) || ListUtils.isListValued(fSearch.getLiveList()) || ListUtils.isListValued(fSearch.getNewsList()) || ListUtils.isListValued(fSearch.getSpecialList()))) {
                    JLog.e("=====search==" + fSearch.toString());
                    no_result.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);
                    view_ll.setVisibility(View.GONE);
                    result_ll.setVisibility(View.VISIBLE);
//                    pageAll=fSearch.getPageAll();
//                    currentPage=fSearch.getPageIndex();
//                    setSeaechData(fSearch);
                    setSearchData(fSearch);
                } else if(index==0){
                    view_ll.setVisibility(View.GONE);
                    result_ll.setVisibility(View.VISIBLE);
                    no_result.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    /**
     * 查询搜索的更多的结果
     * @param keyword
     */
    private void searchForPage(String keyword) {
        KeyBoardUtils.closeKeyboard(this);
        ArrayMap<String, Object> param = new ArrayMap<>();
        param.put("keyword", keyword);
        param.put("siteNumber", Constances.SITE_ID);
        param.put("index", index);
        param.put("option", 1);
        param.put("count", count);
        NetUtils.getNetAdapter().keywordOptionSearchFulltext(getOwnerName(), param, new AbsNetCallBack<SearchResult>(SearchResult.class) {
            @Override
            public void onSuc(SearchResult fSearch) {
                if (fSearch != null ) {
                    JLog.e("=====search==" + fSearch.toString());
                    view_ll.setVisibility(View.GONE);
                    result_ll.setVisibility(View.VISIBLE);
//                    pageAll=fSearch.getPageAll();
//                    currentPage=fSearch.getPageIndex();
//                    setSeaechData(fSearch);
                    setSearchData(fSearch);
                } else {
                    no_result.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                //toast("数据错误");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                onNetFinish();
            }
        });
    }

    private synchronized void onNetFinish() {
        if (refreshLayout.isRefreshing()) {
            refreshLayout.refreshComplete();
        }
        if (refreshLayout.isLoading()) {
            refreshLayout.loadMoreComplete();
        }
    }

    /**
     * 赋值显示搜索结果
     * @param fSearches
     */
    private void setSearchData(SearchResult fSearches) {
        List<NewsItem> newsList = fSearches.getNewsList();
//        List<FProgram> programmeList = fSearches.getProgrammeList();
        List<LiveItem> liveList = fSearches.getLiveList();
        List<AFileItem> anchorList = fSearches.getAnchorList();
        List<TopicItem> specialList = fSearches.getSpecialList();
        List<IListShowData> tempList = new ArrayList<>();
        if (ListUtils.isListValued(anchorList)) {
            AFileItem fileItem = anchorList.get(0);
            if (anchorList.size() > 1) {
                fileItem.setHasMore(true);
            } else {
                fileItem.setHasMore(false);
            }
            tempList.add(fileItem);
        }
        if (ListUtils.isListValued(liveList)) {
            LiveItem liveItem = liveList.get(0);
            if (liveList.size() > 1) {
                liveItem.setHasMore(true);
            } else {
                liveItem.setHasMore(false);
            }
            tempList.add(liveList.get(0));
        }
        if (ListUtils.isListValued(specialList)) {
            if (specialList.size() > 3) {
                for (int i = 0; i < 3; i++) {
                    TopicItem item = specialList.get(i);
                    if (i == 2) {
                        item.setLastItem(true);
                    } else {
                        item.setLastItem(false);
                    }
                    tempList.add(item);
                }
            } else {
                tempList.addAll(specialList);
            }
        }
        if (ListUtils.isListValued(newsList)) {
            if (newsList.size() >= 10) {
                refreshLayout.setLoadMoreEnabled(true);
            } else {
                refreshLayout.setLoadMoreEnabled(false);
            }
            tempList.addAll(newsList);
        } else {
            refreshLayout.setLoadMoreEnabled(false);
        }
//        if (ListUtils.isListValued(newsList)) {
//            tempList.addAll(newsList);
//        }
////        else if (ListUtils.isListValued(programmeList)) {
////            tempList.addAll(programmeList);
////        }
//        else if (ListUtils.isListValued(liveList)) {
//            tempList.addAll(liveList);
//        } else if (ListUtils.isListValued(anchorList)) {
//            tempList.addAll(anchorList);
//        } else if (ListUtils.isListValued(specialList)) {
//            tempList.addAll(specialList);
//        }
//        if (!ListUtils.isListValued(tempList)) {
//            tempList.clear();
//        }
        if (index == 0) {
            if (searchResultAdapter == null) {
                searchResultAdapter = new SearchResultAdapter(this, tempList);
                searchResultAdapter.setOnItemInternalClick(this);
                search_result_list.setAdapter(searchResultAdapter);
            } else {
                searchResultAdapter.setData(tempList);
            }
        } else {
            int pos = searchResultAdapter.getItemCount();
            searchResultAdapter.addDatas(tempList);
            if (pos > 0) {
                searchResultAdapter.notifyItemChanged(pos - 1);
            }
        }
    }

    private void setSeaechData(FSearch fSearches) {
        List<IListShowData> list = new ArrayList<>();
        List<FProgram> proList = fSearches.getProgrammeList();
        List<NewsItem> newsList = fSearches.getNewsList();
        if (!ListUtils.isListValued(proList) && !ListUtils.isListValued(newsList)) {
            if (index == 0) {
                no_result.setVisibility(View.VISIBLE);
                refreshLayout.setVisibility(View.GONE);
            } else {
                refreshLayout.setLoadMoreEnabled(false);
                no_result.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
            }
        } else {
            no_result.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
            Titles titles = null;
            if (ListUtils.isListValued(proList)) {
                titles = new Titles();
                titles.setTitle(getString(R.string.search_topic_contain));
                titles.setViewType(SearchResultAdapter.VIEWTYPE_TOPIC_TITLE);
                list.add(titles);
                for (FProgram programme : proList) {
                    programme.setViewType(SearchResultAdapter.VIEWTYPE_TOPIC_CONTENT);
                }
                list.addAll(proList);
            }
            if (ListUtils.isListValued(newsList)) {
                if (index == 0) {
                    titles = new Titles();
                    titles.setTitle(search_ct.getText().toString().trim());
                    titles.setViewType(SearchResultAdapter.VIEWTYPE_ARTICLE_TITLE);
                    list.add(titles);
                }
                for (NewsItem newsItem : newsList) {
                    newsItem.setViewType(SearchResultAdapter.VIEWTYPE_ARTICLE_CONTENT);
                }
                list.addAll(newsList);
            } else {
                if (index != 0) {
                    refreshLayout.setLoadMoreEnabled(false);
                }
            }
        }
        if (index == 0) {
            if (searchResultAdapter == null) {
                searchResultAdapter = new SearchResultAdapter(this, list);

                search_result_list.setAdapter(searchResultAdapter);

            } else {
                searchResultAdapter.setData(list);
            }
        } else {
            int pos = searchResultAdapter.getItemCount();
            searchResultAdapter.addDatas(list);
            if (pos > 0) {
                searchResultAdapter.notifyItemChanged(pos - 1);
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            String voice = data.getStringExtra(SpeakActivity.SEARCH_KEY);
            if (!TextUtils.isEmpty(voice)) {
                search_ct.setText(voice);
                onRefresh();
                addHistory(voice);
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("行为类型", "主动搜索"));
                GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);

            }
        }
    }

    private OnItemInternalClick hisOnItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            search_ct.setText(searchHisAdapter.getItem(position).getKeywords());
            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "历史搜索"));
            GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);

            if (position == searchHisAdapter.getItemCount() - 1) {
                dialog = initDialog();
                dialog.show();
            } else {
                onRefresh();
//                search(search_ct.getText().toString().trim());
            }
        }
    };

    private AlertDialog initDialog() {
        View view = LayoutInflater.from(this).inflate(R.layout.dia_history, null);
        CustomFontTextView no_ct = (CustomFontTextView) view.findViewById(R.id.dia_history_no);
        CustomFontTextView ok_ct = (CustomFontTextView) view.findViewById(R.id.dia_history_ok);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(view);
        final AlertDialog dialog = builder.create();
        no_ct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        ok_ct.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferencesUtil.setParams(SearchActivity.this, HISTORY_KEY, "");
                setHistoryKey();
                dialog.dismiss();
            }
        });
        return dialog;
    }

    OnItemInternalClick hotItemClick = new OnItemInternalClick() {
        @Override
        public void onItemInternalClick(View itemView, View view, int position) {
            SearchKeyWords hotSearch = hotAdapter.getItem(position);
            if (!TextUtils.isEmpty(hotSearch.getKeywords())) {
                addHistory(hotSearch.getKeywords());
                search_ct.setText(hotSearch.getKeywords());
                onRefresh();
                ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                pairs.add(new Pair<>("行为类型", "热门搜索"));
                GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);

            }
        }
    };

    /**
     * 初始化popup窗口
     */
    private void initSelectPopup() {
        View v = LayoutInflater.from(this).inflate(R.layout.search_popup_list, null);
        mTypeLv = (ListView) v.findViewById(R.id.lv_search_type_popup);
        // 设置适配器
        testDataAdapter = new ArrayAdapter<>(this, R.layout.item_search_menu, typedata);
        mTypeLv.setAdapter(testDataAdapter);

        // 设置ListView点击事件监听
        mTypeLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 在这里获取item数据
                String value = typedata.get(position);
                type = position + 1;
                // 把选择的数据展示对应的TextView上
                mSelectTv.setText(value);
                // 选择完后关闭popup窗口
                typeSelectPopup.dismiss();

                String keyword = search_ct.getText().toString().trim();
                if (!TextUtils.isEmpty(keyword)) {
                    index = 0;
                    search(keyword);
                    ArrayList<Pair<String, String>> pairs = new ArrayList<>();
                    pairs.add(new Pair<>("行为类型", "主动搜索"));
                    GridsumWebDissector.getInstance().trackEvent(SearchActivity.this, "", "搜索", "", 200, pairs);

                }

            }
        });
        typeSelectPopup = new PopupWindow(v, (int) (mSelectTv.getWidth() * 2.5), ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 取得popup窗口的背景图片
        Drawable drawable = ContextCompat.getDrawable(this, R.drawable.bg_search);
        typeSelectPopup.setBackgroundDrawable(drawable);
        typeSelectPopup.setFocusable(true);
        typeSelectPopup.setOutsideTouchable(true);
        typeSelectPopup.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                // 关闭popup窗口
                typeSelectPopup.dismiss();
            }
        });
    }

    @Override
    public void onItemInternalClick(View itemView, View view, int position) {
        Intent intent = new Intent(this, MoreSearchActivity.class);
        int type = 0;
        switch (view.getId()) {
            case R.id.rl_more:
                type = 2;
                break;
            case R.id.tv_live_tag_more:
                type = 3;
                break;
            case R.id.tv_tag_more:
                type = 4;
                break;
        }
        if (intent != null) {
            intent.putExtra(BaseActivity.EX_DATA, search_ct.getText().toString().trim());
            intent.putExtra(EX_TYPE, type);
            startActivity(intent);
        }
    }
}
